import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '../router'
import service from '../config'
import { ElMessage } from 'element-plus'
interface LoginData {
    username: string
    password: string,
}

export const useAuthStore = defineStore('auth', () => {
    const username = ref<string>(localStorage.getItem('username'))
    const token = ref<string | null>(localStorage.getItem('token'))
    const roles = ref<string>(localStorage.getItem('roles'))
    const firms = ref<string>(localStorage.getItem('firms'))
    const userId = ref<string>(localStorage.getItem('userId'))
    const isAuthenticated = ref(!!token.value)
    const login = async (loginData: LoginData) => {
        try {
            const response = await service.post('/auth/login', { ...loginData })
                .then(response => {
                    return response.data
                })
            username.value = response?.username
            token.value = response?.token
            roles.value = response?.roles
            firms.value = response?.firms
            userId.value = response?.userId
            isAuthenticated.value = true
            localStorage.setItem('token', response.token)
            localStorage.setItem('username', response.username)
            localStorage.setItem('roles', response.roles)
            localStorage.setItem('userId', response.userId)
            localStorage.setItem('firms', response.firms)
            return true
        } catch (error) {
            console.log(error);
            ElMessage.error(error)
            return false
        }
    }

    const logout = () => {
        username.value = ''
        token.value = null
        roles.value = ''
        userId.value = ''
        isAuthenticated.value = false
        localStorage.removeItem('token')
        router.push({ name: 'Login' })
    }

    return { username, token, roles, firms, userId,isAuthenticated, login, logout }
})